package com.charles.bigdata.mapreduce.joinuser;

import java.io.IOException;
import java.util.Arrays;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class StepSecond {
	static class SecondMapper extends Mapper<LongWritable, Text, Text, Text> {
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			String[] arr = line.split("\t");
			String friend = arr[0];
			String[] users = arr[1].split(",");
			Arrays.sort(users);
			for (int i = 0; i < users.length; i++) {
				for (int j = i + 1; j < users.length; j++) {
					// 这两个人有共同的好友
					context.write(new Text(users[i] + "-" + users[j]), new Text(friend));
				}

			}
		}
	}

	static class SecondReducer extends Reducer<Text, Text, Text, Text> {
		@Override
		protected void reduce(Text user_user, Iterable<Text> friends, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			final StringBuffer buf = new StringBuffer("");
			for (Text friend : friends) {
				buf.append(friend).append(" ");
			}
			context.write(user_user, new Text(buf.toString()));
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job2 = Job.getInstance(conf);
		job2.setJarByClass(StepSecond.class);

		job2.setMapperClass(SecondMapper.class);
		job2.setReducerClass(SecondReducer.class);

		job2.setOutputKeyClass(Text.class);
		job2.setOutputValueClass(Text.class);

		FileInputFormat.setInputPaths(job2, new Path(args[0]));
		FileOutputFormat.setOutputPath(job2, new Path(args[1]));

		boolean res = job2.waitForCompletion(true);
		System.exit(res ? 0 : 1);
	}
}
